using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.UI;
using Telerik.Web.Mvc;
using Telerik.Web.Mvc.Extensions;
using Telerik.Web.Mvc.UI;
using System.Reflection;
using SiteMapNode = Telerik.Web.Mvc.SiteMapNode;

namespace Cineplex.Contacts.Extensions
{
    public static class HtmlHelpersExtensions
    {
        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, bool isChecked, string id, string label, bool disabled = false)
        {
            var check = isChecked ? " checked=\"checked\"" : "";
            var disabledVal = disabled ? " disabled=\"disabled\"" : "";
            var radio = "<label for=\"" + id + "\"><input type=\"radio\" " + disabledVal + " value=\"" + value + "\" " + check + " id=\"" + id + "\" name=\"" + name + "\" />&nbsp; " + label + "</label>";
            return new MvcHtmlString(radio);
        }

        private static readonly IDictionary<string, int> ControllerToProductIdMap = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
            {
                { "grid", 718 },
                { "menu", 719 },
                { "panelbar", 720 },
                { "tabstrip", 721 }
            };

        public static string DisplayForDateTime(this HtmlHelper html, DateTime? dateTime, string format)
        {
            if (dateTime.HasValue)
            {
                return dateTime.Value.ToString(format);
            }
            return string.Empty;
        }

        public static ContactConfigurator Configurator(this HtmlHelper html, string id)
        {
            return new ContactConfigurator(html).ID(id);
        }
        
        public static string ExampleTitle(this HtmlHelper html)
        {
            XmlSiteMap sitemap = (XmlSiteMap)html.ViewData["telerik.mvc.examples"];
            string controller = (string)html.ViewContext.RouteData.Values["controller"];
            string action = (string)html.ViewContext.RouteData.Values["action"];

            SiteMapNode exampleSiteMapNode = sitemap.RootNode.ChildNodes
                .SelectRecursive(node => node.ChildNodes)
                .FirstOrDefault(node => controller.Equals(node.ControllerName, StringComparison.OrdinalIgnoreCase) &&
                    action.Equals(node.ActionName, StringComparison.OrdinalIgnoreCase));

            if (exampleSiteMapNode != null)
            {
                return exampleSiteMapNode.Title;
            }

            return string.Empty;
        }

        public static string ProductVersion(this HtmlHelper html)
        {
		    Assembly controlAssembly = typeof(Menu).Assembly;
		    Version version = controlAssembly.GetName().Version;

		    int quarter = version.Minor;
		    int versionYear = version.Major;
		    int year = versionYear;
		    int date = version.Build;
		    int month = date / 100;

		    if (month > 12)
		    {
			    year++;
			    month %= 12;
		    }

		    int day = date % 100;

		    return string.Format("Version Q{0} {1}, released {2:d2}/{3:d2}/{4}",
                    quarter, versionYear, month, day, year);
        }

        public static IHtmlString ProductMetaTag(this HtmlHelper html)
        {
            string controller = (string)html.ViewContext.RouteData.Values["controller"];

            if (!ControllerToProductIdMap.ContainsKey(controller))
            {
                return string.Empty.Raw();
            }

            return String.Format("<meta name=\"ProductId\" content=\"{0}\" />", ControllerToProductIdMap[controller]).Raw();
        }


        public static IHtmlString CheckBox(this HtmlHelper html, string id, bool isChecked, string labelText)
        {
            return (html.CheckBox(id, isChecked) + new HtmlElement("label").Attribute("for", id).Html(labelText).ToString()).Raw();
        }

        public static string GetCurrentTheme(this HtmlHelper html)
        {
            return html.ViewContext.HttpContext.Request.QueryString["theme"] ?? "vista";
        }

        public static IHtmlString WaveValidatorLink(this HtmlHelper html)
        {
            var link = new HtmlElement("a")
                .Attributes(new
                {
                    href = String.Format("http://wave.webaim.org/report?url={0}", System.Web.HttpUtility.UrlEncode(html.ViewContext.HttpContext.Request.Url.AbsoluteUri)),
                    id = "wave-validate",
                    @class = "t-button t-button-icontext"
                });

            new HtmlElement("span").AddClass("t-icon wave-logo").AppendTo(link);

            new LiteralNode("Validate with WAVE").AppendTo(link);

            return link.ToString().Raw();
        }      
    }

    public class ContactConfigurator : IDisposable
    {
        public const string CssClass = "configurator";

        private readonly HtmlTextWriter _writer;
        private readonly HtmlHelper _htmlHelper;
        private string _title;
        private string _id;
        private MvcForm _form;

        public ContactConfigurator(HtmlHelper htmlHelper)
        {
            this._htmlHelper = htmlHelper;
            this._writer = new HtmlTextWriter(htmlHelper.ViewContext.Writer);
        }

        public ContactConfigurator Title(string title)
        {
            this._title = title;
            return this;
        }

        public ContactConfigurator ID(string id)
        {            
            this._id = id;
            return this;
        }

        public ContactConfigurator Begin()
        {
            if (this._form == null)
            {
                this._writer.AddAttribute(HtmlTextWriterAttribute.Class, CssClass);         
            }
            
            //this._writer.RenderBeginTag(HtmlTextWriterTag.Div);
            //this._writer.AddAttribute(HtmlTextWriterAttribute.Class, "legend");
            //this._writer.RenderBeginTag(HtmlTextWriterTag.H3);
           // this._writer.Write(this._title);
           // this._writer.RenderEndTag();

            return this;
        }

        public ContactConfigurator End()
        {            

            if (this._form != null)
            {
                this._form.EndForm();
            }

            return this;
        }

        public void Dispose()
        {
            this.End();
        }

        public ContactConfigurator PostTo(string action, string controller)
        {
            string theme = this._htmlHelper.ViewContext.HttpContext.Request.Params["theme"] ?? "Office2010Silver";

            this._form = this._htmlHelper.BeginForm(action, controller, new { theme = theme }, FormMethod.Post, new { @class = CssClass, @id = this._id });

            return this;
        }
    }
}